package com.genghis.rapidcrm;

import com.genghis.rapidcrm.web.view.freemarker.FreeMarkerSharedVariableRegisterAware;
import freemarker.template.SimpleScalar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author xulixin
 */
@Configuration
public class RapidFreeMarkerConfig {

    private static final Logger log = LoggerFactory.getLogger(RapidFreeMarkerConfig.class);

    protected final freemarker.template.Configuration configuration;

    private final FreeMarkerSharedVariableRegisterAware[] sharedVariableRegisters;

    @Value("${server.servlet.context-path:}")
    private String ctxPath;

    public RapidFreeMarkerConfig(freemarker.template.Configuration configuration,
                                 FreeMarkerSharedVariableRegisterAware[] sharedVariableRegisters) {

        this.configuration = configuration;
        this.sharedVariableRegisters = sharedVariableRegisters;
    }

    /**
     * 添加自定义标签
     */
    @PostConstruct
    public void setSharedVariable() {
        ArrayList<String> list = new ArrayList<>();
        list.add("/html_extension.ftl");
        configuration.setAutoIncludes(list);
        HashMap<String, String> importMap = new HashMap<>(2);
        importMap.put("web_macro", "/web_macro.ftl");
        importMap.put("admin_macro", "/admin/admin_macro.ftl");
        configuration.setAutoImports(importMap);
        configuration.setSharedVariable("ctx", new SimpleScalar(ctxPath));
        if (sharedVariableRegisters != null) {
            for (FreeMarkerSharedVariableRegisterAware sharedVariableRegister : sharedVariableRegisters) {
                sharedVariableRegister.getSharedVariables().forEach((name, val) -> configuration.setSharedVariable(name, val));
            }
        }
    }
}
